package com.adk.backend.service.impl;

import com.adk.backend.entity.LxOrderList;
import com.adk.backend.entity.LxRecvLogs;
import com.adk.backend.mapper.RecvLogsMapper;
import com.adk.backend.service.OrderService;
import com.adk.backend.service.RecvLogsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;

/**
 * 收货记录服务实现类
 */
@Slf4j
@Service
public class RecvLogsServiceImpl extends ServiceImpl<RecvLogsMapper, LxRecvLogs> implements RecvLogsService {
    
    @Autowired
    private OrderService orderService;
    
    @Override
    public LxRecvLogs getByOrderIdAndCtnNo(String orderId, Integer ctnNo) {
        return baseMapper.selectByOrderIdAndCtnNo(orderId, ctnNo);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRecv(LxRecvLogs recvLogs) {
        try {
            // 查询订单信息
            LxOrderList order = orderService.getById(recvLogs.getTbOlId());
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }
            
            // 计算体积重（长*宽*高/6000，空运）
            if (order.getShipType() == 1 || order.getShipType() == 3) {
                BigDecimal volume = recvLogs.getCtnL()
                    .multiply(recvLogs.getCtnW())
                    .multiply(recvLogs.getCtnH())
                    .divide(new BigDecimal("6000"), 2, BigDecimal.ROUND_HALF_UP);
                
                // 计费重量取实重和体积重的较大值，并向上取整
                BigDecimal chargeWeight = recvLogs.getCtnWeight().compareTo(volume) > 0 
                    ? recvLogs.getCtnWeight() 
                    : volume;
                recvLogs.setCtnWeightJw(chargeWeight.setScale(0, BigDecimal.ROUND_UP));
                recvLogs.setTotalVwJw(volume.setScale(0, BigDecimal.ROUND_UP));
            }
            
            // 设置添加时间
            if (recvLogs.getAddTime() == null) {
                recvLogs.setAddTime((int) (System.currentTimeMillis() / 1000));
            }
            
            // 保存或更新收货记录
            LxRecvLogs existing = getByOrderIdAndCtnNo(recvLogs.getOrderNo(), recvLogs.getCtnNo());
            if (existing != null) {
                recvLogs.setId(existing.getId());
                recvLogs.setEditTime((int) (System.currentTimeMillis() / 1000));
                this.updateById(recvLogs);
            } else {
                this.save(recvLogs);
            }
            
            // 更新订单收货状态
            updateOrderRecvStatus(order);
            
            return true;
        } catch (Exception e) {
            log.error("保存收货记录失败", e);
            throw e;
        }
    }
    
    @Override
    public Integer countRecvCtnsByOrderId(String orderId) {
        return baseMapper.countRecvCtnsByOrderId(orderId);
    }
    
    /**
     * 更新订单收货状态
     */
    private void updateOrderRecvStatus(LxOrderList order) {
        Integer recvCtns = countRecvCtnsByOrderId(order.getOrderNo());
        
        // 如果已收货箱数等于总箱数，更新订单状态为已收货
        if (recvCtns != null && recvCtns >= order.getTotalCtns()) {
            order.setIsRecv(1);
            order.setRecvTime((int) (System.currentTimeMillis() / 1000));
            order.setStatus(4); // 已收货状态
            order.setCustomerStatus(4);
            order.setLastStatusTime((int) (System.currentTimeMillis() / 1000));
            orderService.updateById(order);
        }
    }
}

